from tkinter.ttk import Combobox
import tkinter
from tkinter.filedialog import askopenfilename, asksaveasfilename
from tkinter import messagebox as msgbox
from PIL import Image, ImageTk
# Set your API key
openai.api_key = "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"


# 基于MySQL的持久化存储
def mysqlPipeLine(inText, outText, type):
    # 获取本机ip 设备信息
    conn = pymysql.connect(host='127.0.0.1', user='root', password='123', port=3306, database='we')
    cursor = conn.cursor()
    sql = 'INSERT INTO chatgpt VALUES(NULL,"%s","%s","%s", NOW(), 0)' % \
          (
              inText, outText, type,
          )
    try:
        cursor.execute(sql)
        conn.commit()
    except Exception as e:
        print(e)
        conn.rollback()
    cursor.close()
    conn.close()


def chat(inText):
    s = "chatGpt:" + inText + "\n \n"
    # 聊天  AI 助手的開放式對話。
    return '今天天气真好哈'


# Menu顶层菜单
def Menu(win):
    # 菜单条
    menubar = tkinter.Menu(win)
    win.config(menu=menubar)

    def func():
        menu1.add_separator()
        menu1.add_command(label="退出", command=win.quit)

    # 点击保存和打开对话框
    def openfile():  # 按钮事件处理函数
        # 显示打开文件对话框，返回选中文件名以及路径
        r = askopenfilename(title='打开文件', filetypes=[('Python', '*.py *.pyw'), ('All Files', '*.*')])
        print(r)

    def savefile():  # 按钮事件处理函数
        # 显示保存文件对话框
        r = asksaveasfilename(title='保存文件', initialdir='d:', initialfile='hello.py')
        print(r)

    # # 创建一个菜单选项
    menu1 = tkinter.Menu(menubar, tearoff=False)

    # 文件下拉菜单
    menu1.add_command(label='打开', command=openfile)
    menu1.add_command(label='保存', command=savefile)
    menu1.add_command(label='退出', command=func)
    # # 向菜单条上添加菜单选项
    menubar.add_cascade(label='文件', menu=menu1)

    # 设计“关于菜单”的下拉菜单功能
    def author():
        msgbox.showinfo('作者', '2023/2/8   zf')

    def about():
        msgbox.showinfo('关于', '用tkinter编写chatGpt图形化调用界面  version 1.1')

    # 创建下拉菜单“关于”，添加到顶层主菜单中
    aboutmenu = tkinter.Menu(menubar, tearoff=False)
    aboutmenu.add_command(label='作者', command=author)
    aboutmenu.add_command(label='关于', command=about)
    menubar.add_cascade(label='about', menu=aboutmenu)


# 初始化Tk()
def initializeTK():
    # 初始化Tk()
    myWindow = tkinter.Tk()
    # 设置标题
    myWindow.title("chatGpt")
    # 设置颜色
    myWindow.config(background="#20B2AA")
    # 设置窗口大小变量
    width = 1000
    height = 800
    # 窗口居中，获取屏幕尺寸以计算布局参数，使窗口居屏幕中央
    screenwidth = myWindow.winfo_screenwidth()
    screenheight = myWindow.winfo_screenheight()
    size_geo = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 2)
    # 设置窗口大小
    myWindow.geometry(size_geo)
    # 设置窗口是否可变长、宽，True：可变，False：不可变
    myWindow.resizable(width=False, height=False)
    # 设置窗口被允许最大调整的范围，与resizble()冲突
    # myWindow.maxsize(1330, 850)
    # 设置窗口被允许最小调整的范围，与resizble()冲突
    # myWindow.minsize(950, 500)
    return myWindow


def guiX():
    # 初始化Tk()
    myWindow = initializeTK()
    # Menu顶层菜单
    Menu(myWindow)

    def run(inText):
        comb = combobox.get()
        if inText == "":
            inText = "Write a love letter for me, with Chinese!"
        txt.insert(END, "-------------------------------------------------------\n \n")
        text = "you:" + inText + "\n \n"
        txt.insert(END, text)
        txt.insert(END, "-------------------------------------------------------\n \n")

        resp = chat(inText)
        mysqlPipeLine(inText, resp, type)

        txt.insert(END, resp)  # 追加显示运算结果
        inp.delete(0, END)  # 清空输

    # 放置图片
    png_image_resized = Image.open('../static/random.jpg')
    tk_image = ImageTk.PhotoImage(png_image_resized)
    # 把图像大小显示到指定的Label
    img = tkinter.Label(myWindow, image=tk_image)
    img.place(x=43, y=40, width=900, height=180)

    # 创建一个标签，显示文本
    model = Label(myWindow, text="模型选择:", bg='#20B2AA', font=('Arial 12 bold'), width=10, height=5)
    model.place(x=26, y=226)

    # 下拉框
    value = StringVar()
    value.set('请选择训练集类型')
    values = ['问答对话', '代码生成', '图片生成', '聊天', '問答', 'SQL翻譯', 'Marv']
    combobox = Combobox(
        master=myWindow,  # 父容器
        height=8,  # 高度,下拉显示的条目数量
        width=20,  # 宽度
        state='readonly',  # 设置状态 normal(可选可输入)、readonly(只可选)、 disabled
        cursor='arrow',  # 鼠标移动时样式 arrow, circle, cross, plus...
        font=('', 12),  # 字体
        textvariable=value,  # 通过StringVar设置可改变的值
        values=values,  # 设置下拉框的选项
    )
    combobox.place(x=135, y=268)

    # 创建一个标签，显示文本
    inText = Label(myWindow, text="输入文本:", bg='#20B2AA', font=('Arial 12 bold'), width=15, height=5)
    inText.place(x=0, y=290)

    # 输入框
    inp = Entry(myWindow, font="Helvetica 10 bold", justify="left", width=22, bg="#FFFFFF", fg="black",
                disabledbackground="#1E6FBA", disabledforeground="yellow", highlightbackground="black",
                highlightcolor="red",
                highlightthickness=0, bd=3)
    inp.place(x=135, y=330, width=465, height=90)

    # 按钮
    btn = Button(myWindow, text='RUN', command=lambda: run(inp.get()), width=10, height=1)
    btn.place(x=520, y=430)

    # Text 在窗体垂直自上而下位置60%处起，布局相对窗体高度40%高的文本框
    txt = Text(myWindow, borderwidth=15, width=135)
    txt.place(x=0, y=460)

    # # 创建滚动条
    scroll = tkinter.Scrollbar(myWindow)
    # 将滚动条填充
    scroll.pack(side=tkinter.RIGHT, fill=tkinter.Y)  # side是滚动条放置的位置，上下左右。fill是将滚动条沿着y轴填充
    # # 将滚动条与文本框关联
    scroll.config(command=txt.yview, width=23)  # 将文本框关联到滚动条上，滚动条滑动，文本框跟随滑动
    txt.config(yscrollcommand=scroll.set)  # 将滚动条关联到文本框

    # 进入消息循环
    myWindow.mainloop()


guiX()
